package com.ztesoft.zsmart.zcm.dialing.util;

import java.util.ArrayList;
import java.util.List;

import com.google.common.base.Strings;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.zcm.core.utils.ZcmSecurityUtil;
import com.ztesoft.zsmart.zcm.dialing.service.probe.kpiTask.mongoDBKpi.MongoDBTarget;

/**
 * @Author xuduan
 * @Date 2021/7/13 0013 14:52
 */
public class MongoDBUtil {

    public static MongoClient getConnect(String ip, Integer port) {
        return new MongoClient(ip, port);
    }

    public static MongoClient getConnectWithIdentify(String ip, Integer port, String userName, String password, String database) {
        List<ServerAddress> adds = new ArrayList<>();
        ServerAddress serverAddress = new ServerAddress(ip, port);
        adds.add(serverAddress);
        List<MongoCredential> credentials = new ArrayList<>();
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, database, password.toCharArray());
        credentials.add(mongoCredential);
        return new MongoClient(adds, credentials);
    }

    public static MongoClient getMongoDatabaseByTarget(MongoDBTarget target) throws BaseAppException {
        if (Strings.isNullOrEmpty(target.getPassword()) || Strings.isNullOrEmpty(target.getUserName())) {
            return getConnect(target.getIp(), target.getPort());
        }
        return getConnectWithIdentify(target.getIp(), target.getPort(), target.getUserName(), ZcmSecurityUtil.decrypt(target.getPassword()), target.getDatabase());
    }

    public String getName() {
        return this.getClass().toString();
    }
}
